// Copyright 2021 comm authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

package comm

import (
	"errors"
	"regexp"
	"strconv"
	"strings"
)

// IsIP 判断是否是ip
func IsIP(ip string) bool {
	reg := `^((0|1\d{0,2}|2(\d?|[0-4]\d|5[0-5])|[3-9]\d?)\.){3}(0|1\d{0,2}|2(\d?|[0-4]\d|5[0-5])|[3-9]\d?)$`
	b, _ := regexp.MatchString(reg, ip)

	return b
}

// IP2Long 将ip转换为int64
func IP2Long(IPStr string) (int64, error) {

	if !IsIP(IPStr) {
		return 0, errors.New("ip format error")
	}

	bits := strings.Split(IPStr, ".")

	var sum int64
	for i, n := range bits {
		bit, _ := strconv.ParseInt(n, 10, 64)
		sum += bit << uint(24-8*i)
	}

	return sum, nil
}
